var turnplate={
    restaurants:[],				//大转盘奖品名称
    colors:[],					//大转盘奖品区块对应背景颜色
    outsideRadius:185,			//大转盘外圆的半径
    textRadius:155,				//大转盘奖品位置距离圆心的距离
    insideRadius:1,			//大转盘内圆的半径
    startAngle:0,				//开始角度

    bRotate:false				//false:停止;ture:旋转
};
$(function () {

    var fn = ABUS.Fn;
    var $el = $('#lotteryContainer');

    //动态添加大转盘的奖品与奖品区域背景颜色
    turnplate.restaurants = ["北京联通5元红包", "北京联通10元红包", "北京联通VIP大礼包", "北京联通VIP大礼包", "北京联通10元红包", "北京联通5元红包"];
    turnplate.urls = ["images/reward_1.png", "images/reward_2.png", "images/reward_3.png", "images/reward_4.png", "images/reward_1.png", "images/reward_2.png"];
    turnplate.colors = ["#ffc455", "#fdf5d1", "#ffc455", "#fdf5d1","#ffc455", "#fdf5d1"];


    var rotateTimeOut = function (){
        $('#wheelcanvas').rotate({
            angle:0,
            animateTo:2160,
            duration:8000,
            callback:function (){
                alert('网络超时，请检查您的网络设置！');
            }
        });
    };

    //旋转转盘 item:奖品位置; txt：提示语;
    var rotateFn = function (item, data){
        var angles = item * (360 / turnplate.restaurants.length) - (360 / (turnplate.restaurants.length*2));
        if(angles<270){
            angles = 270 - angles;
        }else{
            angles = 360 - angles + 270;
        }
        $('#wheelcanvas').stopRotate();
        $('#wheelcanvas').rotate({
            angle:0,
            animateTo:angles+1800,
            duration:8000,          //转盘转动时间
            callback:function (){
                if(item != 4 && item != 8){
                    //中奖
                    fn.win(data);
                }else{
                    //未中奖
                    fn.failed({
                        template:'\
                            <div class="home_layer_1">\
                            <div class="closeLayer"></div>\
                            <div class="failed_text">\
                            <span class="font30 color140">您没有抽中，继续努力哦～</span>\
                            </div>\
                            <div class="receive_submit" data-submit-btn>\
                            <span class="font30 color140">确定</span>\
                            </div>\
                            </div>'
                    })
                }
                turnplate.bRotate = !turnplate.bRotate;
            }
        });
    };

    $el.find('.pointer').on('touchend',function (){
        if(turnplate.bRotate) return;

        var U_num = parseInt($el.find('.num').text());
        if(U_num < 50){
            fn.short({
                template:'\
                <div class="home_layer_2">\
                <div class="closeLayer"></div>\
                <div class="failed_text">\
                <span class="font30 color140">您的U币不足，暂时不能抽奖～</span>\
                </div>\
                <div class="receive_submit" data-submit-btn>\
                <span class="font30 color140">确定</span>\
                </div>\
                </div>',

                onSubmit:function () {
                    fn.closeModal()
                }
            });
            return false
        }
        $el.find('.num').text(U_num-50);
        turnplate.bRotate = !turnplate.bRotate;
        //获取随机数(奖品个数范围内)
        //var item = rnd(1,turnplate.restaurants.length);
        //奖品数量等于10,指针落在对应奖品区域的中心角度[337.5, 292.5, 247.5, 202.5, 157.5, 112.5, 67.5, 22.5]

        var item;
        fn.get({
            url:'./simdata/turntable.json',
            success:function (data) {
                if(data.result ==1){
                    item = parseInt(data.data);
                    rotateFn(item, {
                        title:turnplate.restaurants[item-1],
                        picUrl:turnplate.urls[item-1]
                    });
                }
            },
            error:function () {
                rotateTimeOut()
            }
        });
    });
});

//页面所有元素加载完毕后执行drawRouletteWheel()方法对转盘进行渲染
window.onload=function(){
    drawRouletteWheel();
};

function drawRouletteWheel() {
    var canvas = document.getElementById("wheelcanvas");
    if (canvas.getContext) {
        //根据奖品个数计算圆周角度
        var arc = Math.PI / (turnplate.restaurants.length/2);
        var ctx = canvas.getContext("2d");
        //在给定矩形内清空一个矩形
        ctx.clearRect(0,0,422,422);
        //strokeStyle 属性设置或返回用于笔触的颜色、渐变或模式
        ctx.strokeStyle = "#FFBE04";
        //font 属性设置或返回画布上文本内容的当前字体属性
        ctx.font = '16px "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","\5FAE\8F6F\96C5\9ED1",Arial,sans-serif';
        for(var i = 0; i < turnplate.restaurants.length; i++) {
            var angle = turnplate.startAngle + i * arc;
            ctx.fillStyle = turnplate.colors[i];
            ctx.beginPath();
            //arc(x,y,r,起始角,结束角,绘制方向) 方法创建弧/曲线（用于创建圆或部分圆）
            ctx.arc(211, 211, turnplate.outsideRadius, angle, angle + arc, false);
            ctx.arc(211, 211, turnplate.insideRadius, angle + arc, angle, true);
            ctx.stroke();
            ctx.fill();
            //锁画布(为了保存之前的画布状态)
            ctx.save();

            //----绘制奖品开始----
            ctx.fillStyle = "#313131";
            var text = turnplate.restaurants[i];
            var line_height = 20;
            //translate方法重新映射画布上的 (0,0) 位置
            ctx.translate(211 + Math.cos(angle + arc / 2) * turnplate.textRadius, 211 + Math.sin(angle + arc / 2) * turnplate.textRadius);

            //rotate方法旋转当前的绘图
            ctx.rotate(angle + arc / 2 + Math.PI / 2);

            //截取字符串长度
            if(text.length>4){//奖品名称长度超过一定范围
                text = text.substring(0,4)+"||"+text.substring(4);
                var texts = text.split("||");
                for(var j = 0; j<texts.length; j++){
                    ctx.fillText(texts[j], -ctx.measureText(texts[j]).width / 2, j * line_height);
                }
            }
            //添加对应图标
            if(i == 0||i == 5){
                var img= document.getElementById("reward_1");
                img.onload=function(){
                    ctx.drawImage(img,-25,35,50,50);
                };
                ctx.drawImage(img,-25,35,50,50);
            }
            if(i == 1||i == 4){
                var img= document.getElementById("reward_2");
                img.onload=function(){
                    ctx.drawImage(img,-25,35,50,50);
                };
                ctx.drawImage(img,-25,35,50,50);
            }
            if(i == 2||i == 6){
                var img= document.getElementById("reward_3");
                img.onload=function(){
                    ctx.drawImage(img,-25,35,50,50);
                };
                ctx.drawImage(img,-25,35,50,50);
            }
            if(i == 3||i == 7){
                var img= document.getElementById("reward_4");
                img.onload=function(){
                    ctx.drawImage(img,-25,35,50,50);
                };
                ctx.drawImage(img,-25,35,50,50);
            }
            //把当前画布返回（调整）到上一个save()状态之前
            ctx.restore();
            //----绘制奖品结束----
        }
    }
}